<template>
  <div class="article-edit bg-gray-50 min-h-screen">
    <div class="max-w-7xl mx-auto py-8 px-4">
      <!-- 标题区域 -->
      <div class="mb-8">
        <h1 class="text-2xl font-bold text-gray-900 mb-2">
          {{ route.params.id ? '编辑文章' : '创建新文章' }}
        </h1>
        <p class="text-gray-500">创作新的精彩内容</p>
      </div>

      <el-form
          ref="formRef"
          :model="articleEditStore.articleForm"
          :rules="rules"
          label-width="100px"
          class="bg-white rounded-lg shadow-sm p-6"
      >
        <!-- 标题输入 -->
        <el-form-item label="标题" prop="title">
          <el-input
              v-model="articleEditStore.articleForm.title"
              placeholder="请输入一个吸引人的标题"
              class="title-input"
          />
        </el-form-item>

        <!-- 分类和标签行 -->
        <div class="grid grid-cols-2 gap-4">
          <el-form-item label="分类" prop="category">
            <el-select
                v-model="articleEditStore.articleForm.category"
                placeholder="选择文章分类"
                class="w-full"
            >
              <el-option-group label="体育">
                <el-option label="足球" value="football"/>
                <el-option label="篮球" value="basketball"/>
                <el-option label="NBA" value="nba"/>
                <el-option label="棒球" value="rugby"/>
              </el-option-group>
              <el-option-group label="新闻">
                <el-option label="转会新闻" value="football-transfers"/>
              </el-option-group>
              <el-option-group label="博彩">
                <el-option label="博彩" value="others"/>
              </el-option-group>
            </el-select>
          </el-form-item>

          <el-form-item label="标签" prop="tags">
            <el-select
                v-model="articleEditStore.articleForm.tags"
                multiple
                filterable
                allow-create
                default-first-option
                placeholder="添加相关标签"
                class="w-full"
                :before-create="handleTagBeforeCreate"
                @create="handleTagCreate"
            >
              <el-option
                  v-for="tag in tagOptions"
                  :key="tag.value"
                  :label="tag.label"
                  :value="tag.value"
              />
            </el-select>
          </el-form-item>
        </div>

        <!-- 图片管理区域 -->
        <el-form-item label="媒体资源">
          <div class="media-resources">
            <!-- 封面图片上传 -->
            <div class="cover-upload">
              <p class="upload-title">封面图片</p>
              <el-upload
                  class="avatar-uploader"
                  :action="uploadUrl.data"
                  :show-file-list="false"
                  :on-success="handleThumbnailSuccess"
              >
                <div class="upload-area">
                  <img
                      v-if="articleEditStore.articleForm.thumbnailUrl"
                      :src="articleEditStore.articleForm.thumbnailUrl"
                      class="uploaded-image"
                   alt="">
                  <div v-else class="upload-placeholder">
                    <el-icon><Plus /></el-icon>
                    <span>上传封面</span>
                  </div>
                </div>
              </el-upload>
            </div>

            <!-- 图片资源库按钮 -->
            <div class="resource-library">
              <p class="upload-title">图片资源库</p>
              <el-button @click="showImageSelector">
                <el-icon><Picture /></el-icon>
                打开图片库
              </el-button>
            </div>
          </div>
        </el-form-item>

        <!-- 编辑器区域 -->
        <el-form-item label="内容" prop="contentHtml">
          <Editor
              v-model="articleEditStore.articleForm.contentHtml"
              :height="500"
          />
        </el-form-item>

        <!-- 摘要区域 -->
        <el-form-item label="摘要" prop="summary">
          <el-input
              v-model="articleEditStore.articleForm.summary"
              type="textarea"
              :rows="3"
              placeholder="简短的文章摘要，会显示在列表页面"
              class="summary-input"
          />
        </el-form-item>

        <!-- 操作按钮 -->
        <el-form-item>
          <div class="flex justify-end space-x-4">
            <el-button class="draft-btn" @click="saveDraft">
              <el-icon class="mr-1"><DocumentAdd /></el-icon>
              保存草稿
            </el-button>
            <el-button type="primary" class="publish-btn" @click="publish">
              <el-icon class="mr-1"><Promotion /></el-icon>
              发布文章
            </el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>

    <!-- 图片选择器对话框 -->
    <el-dialog
        v-model="imageDialogVisible"
        title="图片资源库"
        width="80%"
        destroy-on-close
    >
      <ImageSelector ref="imageSelectorRef" @select="handleImageSelect" />
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="imageDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmImageSelection">
          确认选择
        </el-button>
      </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
/* 整体布局样式 */
.article-edit {
  background-color: #f8fafc;
  min-height: 100vh;
}

.article-edit :deep(.el-form-item__label) {
  font-weight: 500;
  color: #374151;
}

/* 页面标题区域 */
.mb-8 {
  background: linear-gradient(145deg, #ffffff 0%, #f1f5f9 100%);
  padding: 2rem;
  border-radius: 12px;
  box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 2rem;
}

/* 表单区域 */
.bg-white {
  background: white;
  border-radius: 16px;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -2px rgba(0, 0, 0, 0.05);
  padding: 2rem;
}

/* 标题输入框 */
.title-input :deep(.el-input__inner) {
  font-size: 1.5rem;
  padding: 1rem;
  border-radius: 8px;
  border: 2px solid #e5e7eb;
  transition: all 0.3s ease;
}

.title-input :deep(.el-input__inner:focus) {
  border-color: #60a5fa;
  box-shadow: 0 0 0 3px rgba(96, 165, 250, 0.2);
}

/* 分类和标签区域 */
.grid {
  margin: 1.5rem 0;
}

:deep(.el-select .el-input__inner) {
  border-radius: 8px;
  border: 2px solid #e5e7eb;
}

/* 媒体资源区域 */
.media-resources {
  display: grid;
  grid-template-columns: 300px 1fr;
  gap: 2rem;
  margin: 1rem 0;
}

.upload-title {
  font-size: 0.875rem;
  font-weight: 500;
  color: #4b5563;
  margin-bottom: 0.75rem;
}

/* 上传区域 */
.upload-area {
  border: 2px dashed #e5e7eb;
  border-radius: 12px;
  height: 240px;
  overflow: hidden;
  transition: all 0.3s ease;
  background: #f9fafb;
}

.upload-area:hover {
  border-color: #60a5fa;
  background: #f3f4f6;
}

.uploaded-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 8px;
}

.upload-placeholder {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #6b7280;
  gap: 0.75rem;
}

.upload-placeholder .el-icon {
  font-size: 2rem;
}

/* 编辑器区域 */
:deep(.editor-container) {
  border-radius: 8px;
  overflow: hidden;
  border: 2px solid #e5e7eb;
}

/* 摘要输入框 */
.summary-input :deep(.el-textarea__inner) {
  border-radius: 8px;
  border: 2px solid #e5e7eb;
  padding: 0.75rem;
  resize: none;
  min-height: 120px;
}

/* 按钮样式 */
.draft-btn {
  background-color: #f3f4f6;
  border: 2px solid #e5e7eb;
  color: #4b5563;
  padding: 0.75rem 1.5rem;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.draft-btn:hover {
  background-color: #e5e7eb;
  color: #374151;
}

.publish-btn {
  background: linear-gradient(145deg, #10b981 0%, #059669 100%);
  border: none;
  color: white;
  padding: 0.75rem 1.5rem;
  border-radius: 8px;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(16, 185, 129, 0.2);
}

.publish-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 6px rgba(16, 185, 129, 0.3);
}

/* 图片选择器对话框 */
:deep(.el-dialog) {
  border-radius: 16px;
  overflow: hidden;
}

:deep(.el-dialog__header) {
  background: #f8fafc;
  margin: 0;
  padding: 1rem 1.5rem;
  border-bottom: 1px solid #e5e7eb;
}

:deep(.el-dialog__body) {
  padding: 1.5rem;
}

:deep(.el-dialog__footer) {
  border-top: 1px solid #e5e7eb;
  padding: 1rem 1.5rem;
}
</style>

<script setup lang="ts">
import {onMounted, ref} from 'vue'
import {useRoute, useRouter} from 'vue-router'
import {useArticleEditStore} from '@/stores/articleEdit'
import Editor from '@/components/article/Edit.vue'
import {DocumentAdd, Plus, Promotion} from '@element-plus/icons-vue'
import {ElMessage} from "element-plus";
import {useTagStore} from '@/stores/tag'
import {useConfigStore} from '@/stores/sysConfig.js'
import ImageSelector from "@/components/article/ImageSelector.vue";

const configStore = useConfigStore()

const tagStore = useTagStore()
const route = useRoute()
const router = useRouter()
const articleEditStore = useArticleEditStore()
const formRef = ref()
// 标签选项
const tagOptions = ref([])

const imageDialogVisible = ref(false)
const imageSelectorRef = ref(null)
const selectedImageUrls = ref([]) // 用于存储选中的图片URL

const editorRef = ref(null)

// 暴露编辑器插入图片的方法
const insertImage = (imageInfo) => {
  if (editorRef.value) {
    editorRef.value.insertImage(imageInfo)
  }
}

defineExpose({
  insertImage
})

// 显示图片选择器
const showImageSelector = () => {
  imageDialogVisible.value = true
}

// 处理图片选择变化（当在ImageSelector中选择图片时触发）
const handleImageSelect = (selectedIds) => {
  // 存储选中的图片ID
  selectedImageUrls.value = selectedIds
}

// 确认选择按钮处理
const confirmImageSelection = () => {
  if (imageSelectorRef.value) {
    const selectedIds = imageSelectorRef.value.getSelected()
    // 获取选中图片的信息
    const selectedImages = imageSelectorRef.value.getSelectedImages() // 需要在ImageSelector组件中添加这个方法

    if (selectedImages && selectedImages.length > 0) {
      // 设置第一张图片作为封面
      articleEditStore.articleForm.thumbnailUrl = selectedImages[0].url

      // 如果需要，也可以把图片插入到编辑器中
      // 这里假设编辑器实例通过 ref 获取
      if (editorRef.value) {
        selectedImages.forEach(image => {
          // 插入图片到编辑器
          editorRef.value.insertImage({
            url: image.url,
            alt: image.originalName
          })
        })
      }
    }

    // 关闭对话框
    imageDialogVisible.value = false
    // 清空选择
    imageSelectorRef.value.clearSelection()
  }
}

// 获取所有标签
const fetchTags = async () => {
  try {
    const { records } = await tagStore.getTags({
      page: 1,
      size: 1000 // 获取足够多的标签
    })
    // 转换格式
    tagOptions.value = records.map(tag => ({
      label: tag.name,
      value: tag.name,
      isSystem: tag.isSystem
    }))
  } catch (error) {
    ElMessage.error('获取标签列表失败')
  }
}

// 标签输入前的验证
const handleTagBeforeCreate = (val) => {
  // 检查标签是否已存在
  const exists = tagOptions.value.some(tag => tag.label.toLowerCase() === val.toLowerCase())
  if (exists) {
    ElMessage.warning('标签已存在')
    return false
  }
  // 这里可以添加其他验证规则
  if (val.length > 20) {
    ElMessage.warning('标签长度不能超过20个字符')
    return false
  }
  return true
}

// 当创建新标签时
const handleTagCreate = async (val) => {
  try {
    // 保存新标签到后端
    await tagStore.addTag({
      name: val,
      category: 'OTHER', // 默认分类
      weight: 0
    })
    // 添加到选项中
    tagOptions.value.push({
      label: val,
      value: val,
      isSystem: false
    })
    ElMessage.success('创建新标签成功')
  } catch (error) {
    ElMessage.error('创建新标签失败')
  }
}

// 表单校验规则
const rules = {
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' },
    { min: 3, max: 100, message: '标题长度在 3 到 100 个字符', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择分类', trigger: 'change' }
  ],
  contentHtml: [
    { required: true, message: '请输入文章内容', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value && value.length < 10) {
          callback(new Error('文章内容至少10个字符'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 上传配置
// 上传URL
const uploadUrl = ref('')
// 获取系统配置
const fetchConfig = async () => {
  try {
    uploadUrl.value = await configStore.fetchConfig('system.upload.url')
  } catch (error) {
    ElMessage.error('获取上传配置失败')
  }
}

// 缩略图上传成功
const handleThumbnailSuccess = (res) => {
  articleEditStore.articleForm.thumbnailUrl = res.data.url
}

// 保存草稿
const saveDraft = async () => {
  try {
    await formRef.value.validate()
    await articleEditStore.save(true)
    await router.push(`/admin-articles/drafts`)
  } catch (error) {
    // 验证失败或保存失败的错误已经处理
  }
}

// 发布文章
const publish = async () => {
  try {
    await formRef.value.validate()
    let newVar = await articleEditStore.save(false);
    if (newVar.code === 200) {
      await router.push('/admin-articles/list')
    }
  } catch (error) {
    // 验证失败或保存失败的错误已经处理
  }
}

onMounted(async () => {
  await fetchConfig()
  await fetchTags()
  const id = route.params.id
  if (id) {
    await articleEditStore.fetchArticleEdit(id as string)
  } else {
    articleEditStore.resetForm()
  }
})
</script>